package com.rabbitmq.provider.config;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ShutdownSignalException;
import org.springframework.amqp.rabbit.connection.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @作者: 林江
 * @创建时间: 2023/11/14
 * @功能: Rabbit的配置信息
 */
@Configuration
public class RabbitConfiguration {
    /**
     * 定义rabbitmq工厂
     *
     * @return
     */
    @Bean
    public CachingConnectionFactory cachingConnectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setHost("192.168.32.128");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("123456");
        factory.setVirtualHost("/");

        // 开始消息的确认机制
        factory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        // 开启消息的返回机制
        factory.setPublisherReturns(true);

        // 注册通道监听器
        factory.addChannelListener(new ChannelListener() {
            @Override
            public void onCreate(Channel channel, boolean transactional) {
                System.out.println("通道创建。。。。。" + channel.getConnection().getClientProvidedName());
            }
        });

        // 注册连接监听器，
        factory.addConnectionListener(new ConnectionListener() {
            // 当mq连接创建时，就触发。
            @Override
            public void onCreate(Connection connection) {
                System.out.println("mq连接创建，连接端口：" + connection.getLocalPort());
            }

            // 当mq连接销毁时，就触发
            @Override
            public void onShutDown(ShutdownSignalException signal) {
                System.out.println("mq连接销毁，销毁信息：" + signal.getMessage());
            }
        });

        // 配置mq连接的命名策略,默认是cachingConnectionFactory#xxxxx
//        factory.setConnectionNameStrategy(connectionNameStrategy());
        return factory;
    }

    /**
     * 创建rabbitmq访问实列模板
     *
     * @return
     */
    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(cachingConnectionFactory());
        return template;
    }

    @Value("${spring.application.name}")
    private String name;

    //    @Bean
    public ConnectionNameStrategy connectionNameStrategy() {
        return new SimplePropertyValueConnectionNameStrategy(name);
    }

}
